using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using FarPoint.Win.Spread;
using FarPoint.Win.Spread.Model;
using FarPoint.Win.Spread.CellType;
using System.Drawing;

namespace Spread.Sparkline.Features
{
    public partial class SparklineGroupsAndSettings : Spread.Common.Features.Sample.BaseSampleControl
    {
        #region ctor
        public SparklineGroupsAndSettings()
        {
            InitializeComponent();
            Name = "Sparkline Groups and Settings";

            InitSpreadSheet(fpSpread.ActiveSheet);
            InitControls();
            fpSpread.SelectionChanged += FpSpread_SelectionChanged;
        }
        #endregion

        #region Private methods
        private void InitSpreadSheet(SheetView sheet)
        {
            fpSpread.AllowCellOverflow = true;
            sheet.SetMultipleRowHeights(0, sheet.RowCount, 24);
            sheet.SetMultipleColumnWidths(0, sheet.ColumnCount, 75);
            sheet.OperationMode = OperationMode.Normal;
            sheet.SelectionPolicy = SelectionPolicy.MultiRange;

            sheet.Columns[6].Width = 120;

            AddSampleSparklines(sheet);
        }

        private void AddSampleSparklines(SheetView sheet)
        {
            Font boldFont = new Font("Segoe", 9, FontStyle.Bold);

            sheet.Cells[4, 1].Text = "Sales Analysis example:";
            sheet.Cells[4, 1].Font = boldFont;
            sheet.SetClip(5, 1, 1, 6, String.Join("\t", "Region", "Q1", "Q2", "Q3", "Q4", "Regional Sales"));
            sheet.Cells[5, 1, 5, 6].HorizontalAlignment = CellHorizontalAlignment.Center;
            sheet.Cells[5, 1, 5, 6].Font = boldFont;
            sheet.Cells[6, 1].Text = "East";
            sheet.Cells[8, 1].Text = "South";
            sheet.Cells[10, 1].Text = "North";
            sheet.Cells[12, 1].Text = "West";

            Random random = new Random();
            CurrencyCellType currencyCell = new CurrencyCellType();
            for (int row = 6; row < 13; row += 2)
            {
                sheet.Cells[row, 2, row, 5].CellType = currencyCell;
                for (int col = 2; col < 6; ++col)
                    sheet.Cells[row, col].Value = random.Next(-200, 200);
            }

            sheet.SparklineContainer.Add(new ExcelSparklineGroup(new ExcelSparklineSetting(), SparklineType.Line));
            sheet.SparklineContainer[0].Add(new ExcelSparkline(6, 6, sheet, new CellRange(6, 2, 1, 4)));
            sheet.SparklineContainer[0].Add(new ExcelSparkline(8, 6, sheet, new CellRange(8, 2, 1, 4)));
            sheet.SparklineContainer.Add(new ExcelSparklineGroup(new ExcelSparklineSetting(), SparklineType.Column));
            sheet.SparklineContainer[1].Add(new ExcelSparkline(10, 6, sheet, new CellRange(10, 2, 1, 4)));
            sheet.SparklineContainer.Add(new ExcelSparklineGroup(new ExcelSparklineSetting(), SparklineType.Winloss));
            sheet.SparklineContainer[2].Add(new ExcelSparkline(12, 6, sheet, new CellRange(12, 2, 1, 4)));
        }

        private void InitControls()
        {
            btnGroup.Click += BtnGroup_Click;
            btnUngroup.Click += BtnUngroup_Click;

            sparklineSettingPanel1.SetSparklineSettingValues(new ExcelSparklineSetting());
            sparklineSettingPanel1.SparklineSettingChanged += SparklineSettingPanel1_SparklineSettingChanged;
            sparklineSettingPanel1.SparklineRendererChanged += SparklineSettingPanel1_SparklineRendererChanged;
        }

        private SparklineType GetSparklineType(ISparklineRenderer sparklineRenderer)
        {
            if (sparklineRenderer is ColumnSparklineRenderer)
                return SparklineType.Column;
            if (sparklineRenderer is WinLossSparklineRenderer)
                return SparklineType.Winloss;
            return SparklineType.Line;
        }

        private ISparklineGroup GetActiveSparklineGroup()
        {
            CellRange range = fpSpread.ActiveSheet.GetSelection(0);
            ISparkline sparkline = fpSpread.ActiveSheet.Cells[range.Row, range.Column].Sparkline?.Data;
            return FindSparklineGroup(fpSpread.ActiveSheet, sparkline);
        }

        private ISparklineGroup FindSparklineGroup(SheetView sheet, ISparkline sparkline)
        {
            if (sparkline == null)
                return null;
            return sheet.SparklineContainer.Where(group => group.Contains(sparkline)).FirstOrDefault();
        }
        #endregion

        #region Event handlers
        private void FpSpread_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            HashSet<ISparklineGroup> sparklineGroups = new HashSet<ISparklineGroup>();
            foreach (var range in fpSpread.ActiveSheet.GetSelections())
            {
                FarPoint.Win.Spread.Sparkline sp = fpSpread.ActiveSheet.Cells[range.Row, range.Column].Sparkline;
                if (sp != null)
                {
                    sparklineGroups.Add(FindSparklineGroup(fpSpread.ActiveSheet, sp.Data));
                }
            }
            
            btnGroup.Enabled = sparklineGroups.Count > 1;
            btnUngroup.Enabled = GetActiveSparklineGroup()?.Count > 1;
            sparklineSettingPanel1.Enabled = sparklineGroups.Count > 0;

            CellRange firstRange = fpSpread.ActiveSheet.GetSelection(0);
            FarPoint.Win.Spread.Sparkline sparkline = fpSpread.ActiveSheet.GetSparkline(firstRange.Row, firstRange.Column);
            if (sparkline != null)
            {
                var group = FindSparklineGroup(fpSpread.ActiveSheet, sparkline.Data);
                var setting = group.Setting as ExcelSparklineSetting;

                sparklineSettingPanel1.SetSparklineSettingValues(setting, GetSparklineType(group.Renderer));
            }
        }

        private void SparklineSettingPanel1_SparklineRendererChanged(object sender, SparklineRendererChangedEventArgs e)
        {
            GetActiveSparklineGroup().Renderer = e.Renderer;
        }

        private void SparklineSettingPanel1_SparklineSettingChanged(object sender, SparklineSettingChangedEventArgs e)
        {
            GetActiveSparklineGroup().Setting = e.SparklineSetting;
        }

        private void BtnUngroup_Click(object sender, EventArgs e)
        {
            List<FarPoint.Win.Spread.Sparkline> sparklines = new List<FarPoint.Win.Spread.Sparkline>();
            foreach (var range in fpSpread.ActiveSheet.GetSelections())
            {
                FarPoint.Win.Spread.Sparkline sparkline = fpSpread.ActiveSheet.Cells[range.Row, range.Column].Sparkline;
                if (sparkline != null)
                    sparklines.Add(sparkline);
            }

            fpSpread.ActiveSheet.UngroupSparkline(sparklines.Select(sparkline => new CellRange(
                sparkline.Data.Row, sparkline.Data.Column, 1, 1)).ToArray());
            btnUngroup.Enabled = false;
        }

        private void BtnGroup_Click(object sender, EventArgs e)
        {
            List<FarPoint.Win.Spread.Sparkline> sparklines = new List<FarPoint.Win.Spread.Sparkline>();
            foreach (var range in fpSpread.ActiveSheet.GetSelections())
            {
                FarPoint.Win.Spread.Sparkline sparkline = fpSpread.ActiveSheet.Cells[range.Row, range.Column].Sparkline;
                if (sparkline != null)
                    sparklines.Add(sparkline);
            }

            ISparklineSetting setting = sparklines[0].Setting;
            var sparklineGroup = fpSpread.ActiveSheet.GroupSparkline(sparklines.Select
                (sparkline => new CellRange(sparkline.Data.Row, sparkline.Data.Column, 1, 1)).ToArray());
            sparklineGroup.Setting = setting;
            btnGroup.Enabled = false;
            btnUngroup.Enabled = true;
        }

        #endregion
    }
}


//
//SparklineGroupsAndSettings.Designer.cs
//


namespace Spread.Sparkline.Features
{
    partial class SparklineGroupsAndSettings
    {
        /// <summary> 
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary> 
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary> 
        /// Required method for Designer support - do not modify 
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.fpSpread = new FarPoint.Win.Spread.FpSpread();
            this.fpSpread_Sheet1 = new FarPoint.Win.Spread.SheetView();
            this.groupBox1 = new System.Windows.Forms.GroupBox();
            this.btnUngroup = new System.Windows.Forms.Button();
            this.btnGroup = new System.Windows.Forms.Button();
            this.label1 = new System.Windows.Forms.Label();
            this.sparklineSettingPanel1 = new Spread.Sparkline.SparklineSettingPanel();
            this.pnlMain.SuspendLayout();
            this.pnlControls.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.fpSpread)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.fpSpread_Sheet1)).BeginInit();
            this.groupBox1.SuspendLayout();
            this.SuspendLayout();
            // 
            // pnlMain
            // 
            this.pnlMain.Controls.Add(this.fpSpread);
            this.pnlMain.Size = new System.Drawing.Size(580, 606);
            // 
            // pnlControls
            // 
            this.pnlControls.Controls.Add(this.sparklineSettingPanel1);
            this.pnlControls.Controls.Add(this.groupBox1);
            this.pnlControls.Size = new System.Drawing.Size(192, 606);
            // 
            // fpSpread
            // 
            this.fpSpread.Dock = System.Windows.Forms.DockStyle.Fill;
            this.fpSpread.Location = new System.Drawing.Point(0, 0);
            this.fpSpread.Name = "fpSpread";
            this.fpSpread.Sheets.AddRange(new FarPoint.Win.Spread.SheetView[] {
            this.fpSpread_Sheet1});
            this.fpSpread.Size = new System.Drawing.Size(580, 606);
            this.fpSpread.Skin = FarPoint.Win.Spread.DefaultSpreadSkins.Office2016White;
            this.fpSpread.StatusBarVisible = true;
            this.fpSpread.TabIndex = 0;
            // 
            // fpSpread_Sheet1
            // 
            this.fpSpread_Sheet1.Reset();
            this.fpSpread_Sheet1.SheetName = "Sheet1";
            // Formulas and custom names must be loaded with R1C1 reference style
            this.fpSpread_Sheet1.ReferenceStyle = FarPoint.Win.Spread.Model.ReferenceStyle.R1C1;
            this.fpSpread_Sheet1.ReferenceStyle = FarPoint.Win.Spread.Model.ReferenceStyle.A1;
            // 
            // groupBox1
            // 
            this.groupBox1.Controls.Add(this.btnUngroup);
            this.groupBox1.Controls.Add(this.btnGroup);
            this.groupBox1.Controls.Add(this.label1);
            this.groupBox1.Dock = System.Windows.Forms.DockStyle.Top;
            this.groupBox1.Location = new System.Drawing.Point(0, 0);
            this.groupBox1.Name = "groupBox1";
            this.groupBox1.Size = new System.Drawing.Size(192, 123);
            this.groupBox1.TabIndex = 0;
            this.groupBox1.TabStop = false;
            this.groupBox1.Text = "Sparkline Grouping";
            // 
            // btnUngroup
            // 
            this.btnUngroup.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 
            | System.Windows.Forms.AnchorStyles.Right)));
            this.btnUngroup.Enabled = false;
            this.btnUngroup.Location = new System.Drawing.Point(38, 89);
            this.btnUngroup.Name = "btnUngroup";
            this.btnUngroup.Size = new System.Drawing.Size(110, 23);
            this.btnUngroup.TabIndex = 2;
            this.btnUngroup.Text = "Ungroup";
            this.btnUngroup.UseVisualStyleBackColor = true;
            // 
            // btnGroup
            // 
            this.btnGroup.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 
            | System.Windows.Forms.AnchorStyles.Right)));
            this.btnGroup.Enabled = false;
            this.btnGroup.Location = new System.Drawing.Point(38, 60);
            this.btnGroup.Name = "btnGroup";
            this.btnGroup.Size = new System.Drawing.Size(110, 23);
            this.btnGroup.TabIndex = 1;
            this.btnGroup.Text = "Group";
            this.btnGroup.UseVisualStyleBackColor = true;
            // 
            // label1
            // 
            this.label1.Dock = System.Windows.Forms.DockStyle.Top;
            this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label1.Location = new System.Drawing.Point(3, 16);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(186, 32);
            this.label1.TabIndex = 0;
            this.label1.Text = "Select multiple Sparklines and Group/Ungroup selected sparklines";
            // 
            // sparklineSettingPanel1
            // 
            this.sparklineSettingPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.sparklineSettingPanel1.Enabled = false;
            this.sparklineSettingPanel1.Location = new System.Drawing.Point(0, 123);
            this.sparklineSettingPanel1.Name = "sparklineSettingPanel1";
            this.sparklineSettingPanel1.Size = new System.Drawing.Size(192, 483);
            this.sparklineSettingPanel1.TabIndex = 1;
            // 
            // SparklineGroupsAndSettings
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Name = "SparklineGroupsAndSettings";
            this.Size = new System.Drawing.Size(773, 606);
            this.pnlMain.ResumeLayout(false);
            this.pnlControls.ResumeLayout(false);
            ((System.ComponentModel.ISupportInitialize)(this.fpSpread)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.fpSpread_Sheet1)).EndInit();
            this.groupBox1.ResumeLayout(false);
            this.ResumeLayout(false);

        }

        #endregion

        private FarPoint.Win.Spread.FpSpread fpSpread;
        private FarPoint.Win.Spread.SheetView fpSpread_Sheet1;
        private SparklineSettingPanel sparklineSettingPanel1;
        private System.Windows.Forms.GroupBox groupBox1;
        private System.Windows.Forms.Button btnUngroup;
        private System.Windows.Forms.Button btnGroup;
        private System.Windows.Forms.Label label1;
    }
}
